import React, { useEffect, useRef } from 'react';
import E from 'wangeditor';
import Cloud from 'leancloud-storage';

export default function RichEditor(props) {
  const editorRef = useRef();
  useEffect(() => {
    const editor = new E(editorRef.current);
    editor.config.zIndex = 10; //调整层级
    //自定义配置菜单
    editor.config.menus = [
      'head',
      'bold',
      'fontSize',
      'fontName',
      'italic',
      'underline',
      'strikeThrough',
      'indent',
      'lineHeight',
      'foreColor',
      'backColor',
      'link',
      'list',
      'todo',
      'justify',
      'quote',
      'emoticon',
      'image',
    ];
    // 失焦获取内容
    editor.config.onblur = function (newHtml) {
      // 把富文本内容暴露出去
      props.onChange(newHtml);
    };
    // 实现图片上传
    editor.config.customUploadImg = function (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // 把图片转换成baes64
      const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.readAsDataURL(img);
        reader.addEventListener('load', () => callback(reader.result));
      };
      getBase64(resultFiles[0], async (base64) => {
        const file = new Cloud.File('cakeimg.png', { base64 });
        const res = await file.save();
        // 上传图片，返回结果，将图片插入到编辑器中
        insertImgFn(res.attributes.url);
      });
    };
    editor.create(); //向指定DOM中渲染编辑器
  }, []);
  return <div ref={editorRef}></div>;
}
